package servlet;

import db.DBSession;
import entity.Admin;
import entity.User;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: LoginServlet
 * @Author: Leo
 * @Description:
 * @Date: 2019/4/18 15:2
 */
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    public static final String ERROR = "<script> alert(\"Error: 账号或密码错误！\"); </script>";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        HttpSession httpSession = request.getSession();
        httpSession.setMaxInactiveInterval(7200);
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        SqlSession sqlSession = DBSession.getSession();

        User user = sqlSession.selectOne("selectByUsername", username);
        Admin admin = sqlSession.selectOne("selectByUserName", username);
        if (user != null) {
            String md5 = sqlSession.selectOne("selectMD5", password+user.getSalt());
            if (user.getPassword().equals(md5)) {
                httpSession.setAttribute("username", username);
                httpSession.setAttribute("password", password);
                response.sendRedirect("a.jsp");
            } else {
                printWriter.write(ERROR);
            }
        } else if (admin != null) {
            String md5 = sqlSession.selectOne("selectMD5", password+admin.getSalt());
            if (admin.getPassword().equals(md5)) {
                httpSession.setAttribute("username", username);
                httpSession.setAttribute("password", password);
                response.sendRedirect("b.jsp");
            } else {
                printWriter.write(ERROR);
            }
        } else {
            printWriter.write(ERROR);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
